using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using ATLib.net;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Excel;
using SampleUHFAt900;
using PVIDUHF.Core;
using System.Data.SqlServerCe;

namespace PVID_UHF_CE_Application
{
    public partial class UHFMain : Form, Util_PowerOn_NET.IUtil_PowerOn
    {
        string ConnectionString = null;

        TagDetails objTG = new TagDetails();
        string TagType = Convert.ToString(MobileConfiguration.Settings["TagType"]);
        string IV = string.Empty;
        #region RFID API members declaration
        public static AT_UHF_NET.CUHFHost rfid;
        Util_PowerOn_NET.CUtil_PowerOn PowerNotify;
        #endregion

        #region "Barcode Initiation Code"
        #region  ########## Play_Sound ##########
        [DllImport("coredll.dll")]
        private static extern int PlaySound(string szSound, IntPtr hModule, int flags);
        private enum PlaySoundFlags : int
        {
            SND_SYNC = 0x0,     // play synchronously (default)
            SND_ASYNC = 0x1,    // play asynchronously
            SND_NODEFAULT = 0x2,    // silence (!default) if sound not found
            SND_MEMORY = 0x4,       // pszSound points to a memory file
            SND_LOOP = 0x8,     // loop the sound until next sndPlaySound
            SND_NOSTOP = 0x10,      // don't stop any currently playing sound
            SND_NOWAIT = 0x2000,    // don't wait if the driver is busy
            SND_ALIAS = 0x10000,    // name is a registry alias
            SND_ALIAS_ID = 0x110000,// alias is a predefined ID
            SND_FILENAME = 0x20000, // name is file name
            SND_RESOURCE = 0x40004, // name is resource name or atom
        };
        public static void Play_Sound(string fileName)
        {
            PlaySound(fileName, IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_ASYNC));
        }
        public static void PlaySuccess()
        {
            PlaySound(@"\Windows\Success.wav", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_ASYNC));
        }
        public static void PlayFail()
        {
            PlaySound(@"\Windows\fail.wav", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_ASYNC));
        }
        #endregion

        #region WM AT570 Key Message Declarations
        internal const int WM_USER = 0x400;
        internal const int WM_KEYDOWN = 0x0100;
        internal const int TRAY_NOTIFY_ALL = WM_USER + 1430;
        #endregion

        #region WM 1D_TC Message Declarations
        internal const int WM_1D_TC_GETDATA = WM_USER + 0x1322;
        #endregion

        //necessary code - 1
        public static CAT570Scan ATAllScan;
        public static uint g_FormCheckNo = 0;
        #endregion

        string EPC = null;
        string UM = null;
        string RM = null;
        public double[] V = new double[9];
        public double[] I = new double[9];
        string ReservedString = string.Empty;
        string EPCString = string.Empty;
        string UserString = string.Empty;

        public UHFMain()
        {
            InitializeComponent();

            #region "RFID Initiation Code"
            PowerNotify = new Util_PowerOn_NET.CUtil_PowerOn(this);
            PowerNotify.AT_PowerNotifyHWND();
            PowerNotify.AT_PowerNotifyEvent();

            rfid = new AT_UHF_NET.CUHFHost();
            rfid.PowerON();
            if (rfid.Open())
            {
                rfid.SET_PowerControl(0);
                sbMain.Text = "Device Operational";
            }
            else
                sbMain.Text = "Open Failed";
            #endregion

            #region "Barcode Initiation Code"
            this.KeyPreview = true;

            //necessary code - 4 (Application Initialize  (once))
            //ATAllScan = new CAT570Scan();
            ATAllScan = new ATLib.net.CAT570Scan();
            ATAllScan.AT_OSKey1_HWND_Net();
            ATAllScan.AT570KeyMsgHandler += new ATLib.net.AT570KeyEventHandler(this.PDA_OSKey_At570KeyMSG);

            //Scanner 1D AT1D_Synchronous
            //necessary code - 5 (Application Initialize  (once))
            //Scan Control Step - 1
            ATAllScan.AT570_1D_TC_Open();
            ATAllScan.AT570_1D_TC_HWND();
            ATAllScan.AT1D_TCMsgHandler += new ATLib.net.AT1D_TCEventHandler(Scanner_OnScanned);
            #endregion

            ConnectionString = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\PVIDDB.sdf;Persist Security Info=False;";
        }

        private void Form1_Closing(object sender, CancelEventArgs e)
        {
            //Step - 3 (Application Close  (once))
            ATAllScan.AT570_OSKey1_HWND_Close();
            ATAllScan.AT570_1D_TC_Close();

        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            g_FormCheckNo = 0;
        }

        // PowerOn Notify Callback
        public void On_status_power()
        {
            // *** Must call this fucntion. ***
            rfid.PowerOnInit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //MessageBox.Show("Form Loading..");
                AppLogWriter.WriteLogEntry("Main From Load.");
                string excelFilepath = Convert.ToString(MobileConfiguration.Settings["FilePath"]);
                lblExcelPath.Text = excelFilepath;
                AppLogWriter.WriteLogEntry("Excel File Loaded");
                btnGo.Enabled = true;
                //MessageBox.Show("Form Loaded.");
                //FileStream stream = File.Open(excelFilepath, FileMode.Open, FileAccess.Read);
                //stream.Close();
                //MessageBox.Show(excelFilepath);
            }
            catch (IOException iex)
            {
                AppLogWriter.WriteErrorLog("Error Loading Excel file.");
                AppLogWriter.WriteErrorLog(iex.Message);
                btnGo.Enabled = false;
                miWriteTag.Enabled = true;
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Loading Excel file.");
                AppLogWriter.WriteErrorLog(ex.Message);
                btnGo.Enabled = false;
                miWriteTag.Enabled = true;
            }
        }


        #region "RFID Tag Methods"
        private void ReadTag()
        {
            try
            {
                AppLogWriter.WriteLogEntry("Begin ReadTag()");
                sbMain.Text = "Read Click";
                ReadRM();
                //MessageBox.Show(RM);
                if (string.IsNullOrEmpty(RM))
                    throw new Exception("Eror Reading tag, Please check the tag.");
                sbMain.Text = "Data Ready, Decoding in progress.";
                AppLogWriter.WriteLogEntry("Data Ready, Decoding in progress.");
                RM = Unicode2String(RM);
                RM = HexString2Ascii(RM);
                //MessageBox.Show(asciiString);
                sbMain.Text = "RM Read: Done";
                AppLogWriter.WriteLogEntry("RM Read: Done");
                AppLogWriter.WriteLogEntry("RM Data: " + RM);
                ReadEPC();
                EPC = Unicode2String(EPC);
                EPC = HexString2Ascii(EPC);
                sbMain.Text = "EPC Read: Done";
                AppLogWriter.WriteLogEntry("EPC Read: Done");
                AppLogWriter.WriteLogEntry("EPC Data: " + EPC);
                ReadUM();
                string _tUM = UM;
                _tUM = UM.Substring(0, 10) + "8" + UM.Substring(11);
                _tUM = _tUM.Replace('A', '.');
                UM = _tUM.Substring(0, 119);
                UM = Unicode2String(UM);
                //UM = HexString2Ascii(UM);
                sbMain.Text = "UM Read: Done";
                AppLogWriter.WriteLogEntry("UM Read: Done");
                AppLogWriter.WriteLogEntry("UM Data: " + UM);
                //MessageBox.Show(RM);
                //MessageBox.Show(EPC);
                //MessageBox.Show(UM);
                sbMain.Text = "Done";
                SplitRM();
                sbMain.Text = "RM Split: Done";
                SplitEPC();
                sbMain.Text = "EPC Split: Done";
                SplitUM();
                sbMain.Text = "UM Split: Done";
            }
            catch (FormatException ex)
            {
                AppLogWriter.WriteErrorLog("Error Reading Tag Data, Exception: " + ex.Message);
                ClearControls();
                MessageBox.Show("Interruption Detected.");
            }
            catch (IndexOutOfRangeException ex)
            {
                AppLogWriter.WriteErrorLog("Error Reading Tag Data, Exception: " + ex.Message);
                ClearControls();
                MessageBox.Show("Multiple Tags Detected.");
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Reading Tag Data, Exception: " + ex.Message);
                ClearControls();
                MessageBox.Show(ex.Message);
            }
        }
        private void ReadEPC()
        {
            sbMain.Text = "Init Read EPC";
            string Data = new string(new char[1024]);
            AT_UHF_NET.AccessResult accessResult = AT_UHF_NET.AccessResult.Unknown;
            rfid.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, true);
            accessResult = rfid.BankSelectRead_Done(Data,
                                    AT_UHF_NET.MEMBANK_CODE.BANK_EPC,
                                    2, 6);
            string temp = rfid.GET_LAST_ERROR();
            sbMain.Text = "EPC Read Done";
            if (temp.Equals("OK"))
            {
                EPC = Data;
                sbMain.Text = "Data loaded to EPC Variable";
            }
            else
                sbMain.Text = "Error Reading EPC: " + temp;
        }

        private void ReadUM()
        {
            string Data = new string(new char[128]);
            AT_UHF_NET.AccessResult accessResult = AT_UHF_NET.AccessResult.Unknown;
            rfid.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, true);
            accessResult = rfid.BankSelectRead_Done(Data,
                                    AT_UHF_NET.MEMBANK_CODE.BANK_USER,
                                    0, 32);
            string temp = rfid.GET_LAST_ERROR();
            if (temp.Equals("OK"))
                UM = Data;
            else
                sbMain.Text = "Error Reading UM: " + temp;
        }

        private void ReadRM()
        {
            string Data = new string(new char[16]);
            AT_UHF_NET.AccessResult accessResult = AT_UHF_NET.AccessResult.Unknown;
            rfid.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, true);
            accessResult = rfid.BankSelectRead_Done(Data,
                                    AT_UHF_NET.MEMBANK_CODE.BANK_RESERVED,
                                    0, 4);
            string temp = rfid.GET_LAST_ERROR();
            if (temp.Equals("OK"))
                RM = Data;
            else
            {
                sbMain.Text = "Error Reading RM: " + temp;
                throw new Exception("Error Reading RM: " + temp);
            }
        }

        public void SplitRM()
        {
            try
            {
                AppLogWriter.WriteLogEntry("RM Split Start");
                AppLogWriter.WriteLogEntry("RMData: " + RM);
                if (TagType.Equals("Philips"))
                {
                    AppLogWriter.WriteLogEntry("TagType: Philips.");
                    txtSCName.Text = RM.Substring(0, 2);
                    txtPVCountry.Text = RM.Substring(2, 2);
                    txtSCCountry.Text = RM.Substring(4, 2);
                    txtICEName.Text = RM.Substring(6, 2);
                }
                else if (TagType.Equals("Alien"))
                {
                    AppLogWriter.WriteLogEntry("TagType: Alien.");
                    txtPVName.Text = RM.Substring(0, 7);
                    txtSCName.Text = txtPVName.Text;
                    //txtPVDate.Text = RM.Substring(2, 4);
                    txtPVCountry.Text = RM.Substring(7, 1);
                    txtSCCountry.Text = txtPVCountry.Text;
                }
                AppLogWriter.WriteLogEntry("RM Split End");
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Spliting RM Data, Exception Message: " + ex.Message);
                throw ex;
            }
        }

        public void SplitEPC()
        {
            try
            {
                AppLogWriter.WriteLogEntry("EPC Split Start");
                AppLogWriter.WriteLogEntry("EPCData: " + EPC);
                if (TagType.Equals("Philips"))
                {
                    AppLogWriter.WriteLogEntry("TagType: Philips.");
                    txtPeakWattage.Text = EPC.Substring(0, 5);
                    txtPVDate.Text = EPC.Substring(5, 5);
                    txtPVName.Text = EPC.Substring(10, 2);
                }
                else if (TagType.Equals("Alien"))
                {
                    AppLogWriter.WriteLogEntry("TagType: Alien.");
                    txtPVCountry.Text = txtPVCountry.Text + EPC.Substring(0, 2);
                    txtSCCountry.Text = txtPVCountry.Text;
                    txtICEName.Text = EPC.Substring(2, 6);
                    txtPVUSN.Text = EPC.Substring(8, 1);
                }
                AppLogWriter.WriteLogEntry("EPC Split End");
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Spliting EPC Data, Exception Message: " + ex.Message);
                throw ex;
            }
        }

        public void SplitUM()
        {
            try
            {
                AppLogWriter.WriteLogEntry("UM Split Start");
                AppLogWriter.WriteLogEntry("UM Data: " + UM);
                if (TagType.Equals("Philips"))
                {
                    txtSCDate.Text = UM.Substring(0, 4);
                    txtPVUSN.Text = UM.Substring(4, 5);
                    txtModelNo.Text = UM.Substring(9, 3);
                    txtICEDate.Text = UM.Substring(12, 4);
                    txtIm.Text = UM.Substring(16, 3);
                    txtVMax.Text = UM.Substring(19, 4);
                    txtFF.Text = UM.Substring(23, 4);
                    int remLength = UM.Length - 27;
                    string[] iv = new string[2];
                    //int _index = UM.Substring(27).IndexOf("00");//Earlier we were using '00' as delimiter for seperating the points. now we are spliting based out of position.
                    iv[0] = UM.Substring(28, 16);
                    AppLogWriter.WriteLogEntry("I Points: " + iv[0]);
                    //iv[1] = UM.Substring(27 + _index + 2);//Earlier we were using '00' as delimiter for seperating the points, thats the reason we are using + 2 after addign index. now we are spliting based out of position.
                    AppLogWriter.WriteLogEntry("UM VPoints: " + UM.Substring(28 + 16));
                    iv[1] = UM.Substring(28 + 16, 20);
                    AppLogWriter.WriteLogEntry("V Points: " + iv[1]);
                    //MessageBox.Show(iv[0]);
                    //MessageBox.Show(iv[1]);
                    //MessageBox.Show(UM);
                    //MessageBox.Show(UM.Substring(27));
                    I[0] = Convert.ToDouble(txtIm.Text);
                    V[0] = Convert.ToDouble(0);
                    for (int i = 0; i < 5; i++)
                    {
                        //I[i] = new double();
                        I[i + 1] = Convert.ToDouble(iv[0].Substring(i * 4, 4));
                        //MessageBox.Show(I[i+1].ToString());
                    }
                    for (int i = 0; i < 5; i++)
                    {
                        //V[i] = new double();
                        V[i + 1] = Convert.ToDouble(iv[1].Substring(i * 5, 5));
                        //MessageBox.Show(V[i+1].ToString());
                    }
                    I[6] = Convert.ToDouble(0);
                    V[6] = Convert.ToDouble(txtVMax.Text);

                }
                else if (TagType.Equals("Alien"))
                {
                    txtPVUSN.Text = txtPVUSN.Text + UM.Substring(0, 9);
                    txtModelNo.Text = UM.Substring(9, 11);
                    txtPVDate.Text = UM.Substring(20, 6);
                    txtSCDate.Text = txtPVDate.Text;
                    txtICEDate.Text = UM.Substring(26, 6);
                    txtPeakWattage.Text = UM.Substring(32, 6);
                    txtIm.Text = UM.Substring(38, 3);
                    txtVMax.Text = UM.Substring(41, 5);
                    txtFF.Text = UM.Substring(46, 2);
                    txtIsc.Text = UM.Substring(48, 4);
                    txtVoc.Text = UM.Substring(52, 4);
                    int remLength = UM.Length - 56;


                    string[] iv = new string[2];
                    iv[0] = UM.Substring(56, 27);
                    AppLogWriter.WriteLogEntry("I Points: " + iv[0]);
                    iv[1] = UM.Substring(56 + 27);
                    AppLogWriter.WriteLogEntry("V Points: " + iv[1]);

                    for (int i = 0; i < 9; i++)
                    {
                        //I[i] = new double();
                        I[i] = Convert.ToDouble(iv[0].Substring(i * 3, 3));
                        //MessageBox.Show(I[i+1].ToString());
                    }
                    for (int i = 0; i < 9; i++)
                    {
                        //V[i] = new double();
                        V[i] = Convert.ToDouble(iv[1].Substring(i * 4, 4));
                        //MessageBox.Show(V[i+1].ToString());
                    }
                } AppLogWriter.WriteLogEntry("UM Split End");

            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Spliting UM Data, Exception Message: " + ex.Message);
                throw ex;
            }
        }

        public void SplitUM(TagTypes tagType)
        {
            try
            {
                AppLogWriter.WriteLogEntry("UM Split Start");
                txtSCDate.Text = UM.Substring(0, 4);
                txtPVUSN.Text = UM.Substring(4, 5);
                txtModelNo.Text = UM.Substring(9, 3);
                txtICEDate.Text = UM.Substring(12, 4);
                txtIm.Text = UM.Substring(16, 3);
                txtVMax.Text = UM.Substring(19, 4);
                txtFF.Text = UM.Substring(23, 4);
                int remLength = UM.Length - 27;
                string[] iv = new string[2];
                int _index = UM.Substring(27).IndexOf("00");
                iv[0] = UM.Substring(27, _index);
                AppLogWriter.WriteLogEntry("I Points: " + iv[0]);
                iv[1] = UM.Substring(27 + _index + 2);
                AppLogWriter.WriteLogEntry("V Points: " + iv[1]);
                //MessageBox.Show(iv[0]);
                //MessageBox.Show(iv[1]);
                //MessageBox.Show(UM);
                //MessageBox.Show(UM.Substring(27));
                I[0] = Convert.ToDouble(txtIm.Text);
                V[0] = Convert.ToDouble(0);
                for (int i = 0; i < 5; i++)
                {
                    //I[i] = new double();
                    I[i + 1] = Convert.ToDouble(iv[0].Substring(i * 3, 3));
                    //MessageBox.Show(I[i+1].ToString());
                }
                for (int i = 0; i < 5; i++)
                {
                    //V[i] = new double();
                    V[i + 1] = Convert.ToDouble(iv[1].Substring(i * 4, 4));
                    //MessageBox.Show(V[i+1].ToString());
                }
                I[6] = Convert.ToDouble(0);
                V[6] = Convert.ToDouble(txtVMax.Text);
                AppLogWriter.WriteLogEntry("UM Split End");
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error Spliting UM Data, Exception Message: " + ex.Message);
                throw ex;
            }
        }
        private string Unicode2String(string InputMemory)
        {
            string unicodeString = InputMemory;

            // Create two different encodings.
            Encoding ascii = Encoding.ASCII;
            Encoding unicode = Encoding.Unicode;

            // Convert the string into a byte[].
            byte[] unicodeBytes = unicode.GetBytes(unicodeString);

            // Perform the conversion from one encoding to the other.
            byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

            // Convert the new byte[] into a char[] and then into a string.
            // This is a slightly different approach to converting to illustrate
            // the use of GetCharCount/GetChars.
            char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
            ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
            string asciiString = new string(asciiChars);
            return asciiString;
        }

        private string HexString2Ascii(string hexString)
        {
            StringBuilder sb = new StringBuilder();
            //MessageBox.Show(hexString.Length.ToString());
            for (int i = 0; i <= hexString.Length - 2; i += 2)
            {
                //MessageBox.Show(hexString.Substring(i, 2));
                if (String.IsNullOrEmpty(hexString.Substring(i, 2).Trim()))
                    return sb.ToString();
                try
                {
                    sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
                }
                catch (Exception ex)
                { return sb.ToString(); }
            }
            return sb.ToString();
        }
        #endregion

        #region "Barcode API Methods"
        public void PDA_OSKey_At570KeyMSG(long MSGStatus, long KeyStatus, long StatusUpDown)
        {
            switch (MSGStatus)
            {
                case (int)TRAY_NOTIFY_ALL:		//PDA Hardware KeyPad
                    if (KeyStatus == (long)Keys.F7 | KeyStatus == (long)Keys.F8 //PDA Keypad Fn7~Fn8(FN+ Add Key)
                        )	//Side Right KEY	
                    {
                        if (StatusUpDown == 0)	//PDA Hardware KEY DOWN
                        {
                            ATAllScan.AT570_1D_TC_ScanStart();
                        }
                        else					//PDA Hardware KEY Up
                        {
                            ATAllScan.AT570_1D_TC_ScanStop();
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        public void Scanner_OnScanned(long MSGStatus, long KeyStatus, long StatusUpDown)
        {
            AppLogWriter.WriteLogEntry("Barcode Scan Started.");
            switch (MSGStatus)
            {
                case (int)WM_1D_TC_GETDATA:
                    if (StatusUpDown == (long)1)	//SCAN SUCCESS
                    {
                        //Scan Sucess
                        PlaySuccess();
                        //Send Barcode Value to Popup Form(Foreground Window)
                        if (g_FormCheckNo == 0)	//Barcode Result Value Sending to Form1
                        {
                            this.GetResultData(ATAllScan.szBarValue, ATAllScan.szBarTypeName, ATAllScan.szBarTypeID);
                        }
                        ATAllScan.AT570_VibratorONOFF(true);
                        System.Threading.Thread.Sleep(400);
                        ATAllScan.AT570_VibratorONOFF(false);
                    }
                    else
                    {
                        PlayFail();
                        if (g_FormCheckNo == 0)		    //Barcode Result Fail Value Sending to Form1
                        {
                            this.GetResultData("Scan Fail", "", "");
                        }
                    }
                    break;
                default:
                    break;
            }
            AppLogWriter.WriteLogEntry("Barcode Scan Ended.");
        }
        #endregion

        public void GetResultData(string sBarValue, string szBarTypeName, string szBarTypeID)
        {
            AppLogWriter.WriteLogEntry("Before Barcode Result.");
            this.txtBarcode.Text = sBarValue;
            AppLogWriter.WriteLogEntry("After Barcode Result, Data: " + sBarValue);
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                if (!txtBarcode.Text.Equals(string.Empty))
                {
                    //ReadFromExcel();
                    btnGo.Enabled = false;
                    sbMain.Text = "Reading from DB..";
                    ReadFromDB(txtBarcode.Text);
                }
                else
                {
                    AppLogWriter.WriteLogEntry("Barcode is empty.");
                    sbMain.Text = "Barcode is empty";
                }
            }
            catch (IOException ex)
            {
                AppLogWriter.WriteErrorLog("IO Exception in btnGo, Exception: " + ex.Message);
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Exception in btnGo, Exception: " + ex.Message);
                MessageBox.Show(ex.Message);
            }
            btnGo.Enabled = true;
        }

        private DataTable LoadDataFromDB(string Barcode)
        {
            try
            {
                DataTable data = null;
                using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
                {
                    if (connection.State != ConnectionState.Open)
                    {
                        connection.Open();
                    }

                    using (SqlCeCommand cmdSelect = connection.CreateCommand())
                    {
                        AppLogWriter.WriteLogEntry("Barcode: " + Barcode);
                        cmdSelect.CommandText = "SELECT * FROM TagDetails where USN='" + Barcode + "';";
                        cmdSelect.CommandType = CommandType.Text;
                        DataSet ds = new DataSet();
                        SqlCeDataAdapter sceda = new SqlCeDataAdapter(cmdSelect);
                        sceda.Fill(ds);
                        data = ds.Tables[0];

                        //using (SqlCeDataReader reader = cmdSelect.ExecuteReader())
                        //{
                        //    if (reader.Read())
                        //    {
                        //        data.Load(reader);
                        //    }
                        //}
                    }
                    if (connection.State != ConnectionState.Closed)
                    {
                        connection.Close();
                    }
                    return data;
                }
            }
            catch (SqlCeException ex)
            {
                throw ex;
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void ReadFromDB(string Barcode)
        {
            miReadTag.Enabled = false;
            DataTable result = null;
            result = LoadDataFromDB(Barcode);
            AppLogWriter.WriteLogEntry("Loaded Data to dataset.");
            //MessageBox.Show(result.Tables[0].Rows.Count.ToString());
            DataRow[] selectedRows = result.Select("USN='" + txtBarcode.Text.Trim() + "'");
            //MessageBox.Show(selectedRows.Length.ToString());
            AppLogWriter.WriteLogEntry("Applied Filter to dataset, Selected Rows: " + selectedRows.Length);
            if (selectedRows.Length != 0)
            {
                LoadData(selectedRows[0], false);
                miWriteTag.Enabled = true;
                tpWriteTag.Focus();
                sbMain.Text = "Data Read to 'Write Tag' Tab.";
            }
            else
            {
                AppLogWriter.WriteLogEntry("No Matching Records Found!, Barocde: " + txtBarcode.Text + ".");
                sbMain.Text = "No Matching Records Found!";
            }
        }

        private void ReadFromExcel()
        {
            miReadTag.Enabled = false;
            string filePath = lblExcelPath.Text;//@"\Flash Disk\data1.xls";
            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            AppLogWriter.WriteLogEntry("Excelreader Initiated, File Path: " + filePath);
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result = excelReader.AsDataSet();
            AppLogWriter.WriteLogEntry("Loaded Data to dataset.");
            //MessageBox.Show(result.Tables[0].Rows.Count.ToString());
            DataRow[] selectedRows = result.Tables[0].Select("USN='" + txtBarcode.Text.Trim() + "'");
            //MessageBox.Show(selectedRows.Length.ToString());
            AppLogWriter.WriteLogEntry("Applied Filter to dataset, Selected Rows: " + selectedRows.Length);
            if (selectedRows.Length != 0)
            {
                LoadData(selectedRows[0]);
                miWriteTag.Enabled = true;
                tpWriteTag.Focus();
                sbMain.Text = "Data Read to 'Write Tag' Tab.";
            }
            else
            {
                AppLogWriter.WriteLogEntry("No Matching Records Found!, Barocde: " + txtBarcode.Text + ".");
                sbMain.Text = "No Matching Records Found!";
            }
        }
        /// <summary>
        /// Used to load data from datatable to fields
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="isExcel"></param>
        private void LoadData(DataRow dr, Boolean isExcel)
        {
            try
            {
                AppLogWriter.WriteLogEntry("Begin LoadData from Excel.");
                txtPVName1.Text = Convert.ToString(dr[1]).Substring(0, 7);
                if (!string.IsNullOrEmpty(dr[2].ToString()))
                {
                    AppLogWriter.WriteLogEntry("Reading PV Date.");
                    DateTime PVDate = Convert.ToDateTime(dr[2]);
                    txtPVDate1.Text = PVDate.Month.ToString("00") + PVDate.Year.ToString();
                    AppLogWriter.WriteLogEntry("PV Date: " + txtPVDate1.Text);
                }
                else
                    AppLogWriter.WriteLogEntry("PV Date not found.");
                txtPVCountry1.Text = Convert.ToString(dr[3]).ToUpper().Substring(0, 3);
                string refStr = Convert.ToString(dr[4]);
                txtPVUSN1.Text = refStr.Substring(0, 10);
                refStr = Convert.ToString(dr[5]).Replace("-", "");
                txtModelNo1.Text = refStr.Substring(0, 11);
                //MessageBox.Show("B PW");
                txtPeakWattage1.Text = Convert.ToDouble(dr[6]).ToString("000.00");
                //MessageBox.Show("A PW");
                txtIm1.Text = Convert.ToDouble(dr[7]).ToString("0.0");
                txtVMax1.Text = Convert.ToDouble(dr[8]).ToString("00.00");
                refStr = Convert.ToDouble(dr[9]).ToString("0.00");
                int refIndex = refStr.IndexOf('.');
                if (refIndex != -1)
                    refStr = refStr.Substring(refIndex + 1, 2);
                else
                    refStr = refStr.Substring(0, 2);
                txtFF1.Text = refStr;
                txtSCName1.Text = txtPVName1.Text;
                txtSCDate1.Text = txtPVDate1.Text;
                txtSCCountry1.Text = txtPVCountry1.Text;
                //if (!string.IsNullOrEmpty(dr[10].ToString()))
                //    txtSCName1.Text = Convert.ToString(dr[10]).Substring(0, 2);
                //else
                //    AppLogWriter.WriteLogEntry("SC Name not found.");
                //if (!string.IsNullOrEmpty(dr[11].ToString()))
                //{
                //    AppLogWriter.WriteLogEntry("Reading SC Date.");
                //    DateTime SCDate = DateTime.FromOADate(Convert.ToDouble(dr[11]));
                //    txtSCDate1.Text = SCDate.Year.ToString().Substring(2) + SCDate.Month.ToString("00");
                //    AppLogWriter.WriteLogEntry("SC Date: " + txtSCDate1.Text);
                //}
                //else
                //    AppLogWriter.WriteLogEntry("SC Date not found.");
                //if (!string.IsNullOrEmpty(dr[12].ToString()))
                //    txtSCCountry1.Text = Convert.ToString(dr[12]).ToUpper().Substring(0, 2);
                //else
                //    AppLogWriter.WriteLogEntry("SC Country not found.");
                if (!string.IsNullOrEmpty(dr[13].ToString()))
                {
                    AppLogWriter.WriteLogEntry("Reading ICE Date.");
                    DateTime IECDate = Convert.ToDateTime(dr[13]);
                    txtICEDate1.Text = IECDate.Month.ToString("00") + IECDate.Year.ToString();
                    AppLogWriter.WriteLogEntry("ICE Date: " + txtICEDate1.Text);
                }
                else
                    AppLogWriter.WriteLogEntry("IEC Date not found.");
                txtICEName1.Text = Convert.ToString(dr[14]).ToUpper().Substring(0, 6);
                txtIsc1.Text = Convert.ToDouble(dr[15]).ToString("0.00");
                txtVoc1.Text = Convert.ToDouble(dr[16]).ToString("00.0");

                //MessageBox.Show("Done");

                for (int i = 17; i <= 34; i++)
                {
                    if (dr[i].ToString().Equals(string.Empty))
                        dr[i] = 0;
                        //throw new Exception("Err: Either of IV Points are null.");
                }

                txtIpoints1.Text = Convert.ToDouble(dr[17]).ToString("0.0").Substring(0, 3) +
                            (Convert.ToDouble(dr[18]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[19]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[20]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[21]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[22]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[23]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[24]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[25]).ToString("0.0").Substring(0, 3));
                txtVPoints1.Text = (Convert.ToDouble(dr[26]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[27]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[28]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[29]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[30]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[31]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[32]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[33]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[34]).ToString("00.0").Substring(0, 4));
                txtIpoints1.ReadOnly = true;
                txtVPoints1.ReadOnly = true;
                AppLogWriter.WriteLogEntry("I Points: " + txtIpoints1.Text);
                AppLogWriter.WriteLogEntry("V Points: " + txtVPoints1.Text);
                IV = txtIpoints1.Text + txtVPoints1.Text;
                AppLogWriter.WriteLogEntry("IV Points: " + IV);
                //MessageBox.Show(IV.ToString());
                string[] iv = new string[2];
                iv[0] = txtIpoints1.Text;
                iv[1] = txtVPoints1.Text;
                //I[0] = Convert.ToDouble(txtIm1.Text);
                //V[0] = Convert.ToDouble(0);
                for (int i = 0; i < 9; i++)
                {
                    //I[i] = new double();
                    I[i] = Convert.ToDouble(Convert.ToDouble(dr[17 + i]).ToString("0.0").Substring(0, 3));
                    AppLogWriter.WriteLogEntry(String.Format("I[{0}] : {1}", i.ToString(), I[i]));
                    //MessageBox.Show(I[i+1].ToString());
                }
                for (int i = 0; i < 9; i++)
                {
                    //V[i] = new double();
                    V[i] = Convert.ToDouble((Convert.ToDouble(dr[26 + i]).ToString("00.0").Substring(0, 4)));
                    AppLogWriter.WriteLogEntry(String.Format("V[{0}] : {1}", i.ToString(), V[i]));
                    //MessageBox.Show(V[i+1].ToString());
                }
                //I[4] = Convert.ToDouble(0);
                //V[4] = Convert.ToDouble(txtVMax1.Text);
                AppLogWriter.WriteLogEntry("Loaded data till I[9] and V[9].");

                //AppLogWriter.WriteLogEntry("ReservedString: " + ReservedString);
                //AppLogWriter.WriteLogEntry("EPCString: " + EPCString);
                //AppLogWriter.WriteLogEntry("UserString: " + UserString);
                AppLogWriter.WriteLogEntry("End LoadData from Excel.");
                miShowGraph.Enabled = true;
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error loading data from Excel, Exception: " + ex.Message);
                throw ex;
            }
        }
        private void LoadData(DataRow dr)
        {
            try
            {
                AppLogWriter.WriteLogEntry("Begin LoadData from Excel.");
                txtPVName1.Text = Convert.ToString(dr[1]).Substring(0, 7);
                if (!string.IsNullOrEmpty(dr[2].ToString()))
                {
                    AppLogWriter.WriteLogEntry("Reading PV Date.");
                    DateTime PVDate = DateTime.FromOADate(Convert.ToDouble(dr[2]));
                    txtPVDate1.Text = PVDate.Month.ToString("00") + PVDate.Year.ToString();
                    AppLogWriter.WriteLogEntry("PV Date: " + txtPVDate1.Text);
                }
                else
                    AppLogWriter.WriteLogEntry("PV Date not found.");
                txtPVCountry1.Text = Convert.ToString(dr[3]).ToUpper().Substring(0, 3);
                string refStr = Convert.ToString(dr[4]);
                txtPVUSN1.Text = refStr.Substring(0, 10);
                refStr = Convert.ToString(dr[5]).Replace("-", "");
                txtModelNo1.Text = refStr.Substring(0, 11);
                //MessageBox.Show("B PW");
                txtPeakWattage1.Text = Convert.ToDouble(dr[6]).ToString("000.00");
                //MessageBox.Show("A PW");
                txtIm1.Text = Convert.ToDouble(dr[7]).ToString("0.0");
                txtVMax1.Text = Convert.ToDouble(dr[8]).ToString("00.00");
                refStr = (dr[9]).ToString();
                int refIndex = refStr.IndexOf('.');
                if (refIndex != -1)
                    refStr = refStr.Substring(refIndex, 2);
                else
                    refStr = refStr.Substring(0, 2);
                txtFF1.Text = refStr;
                txtSCName1.Text = txtPVCountry1.Text;
                txtSCDate1.Text = txtPVDate1.Text;
                txtSCCountry1.Text = txtPVCountry1.Text;
                //if (!string.IsNullOrEmpty(dr[10].ToString()))
                //    txtSCName1.Text = Convert.ToString(dr[10]).Substring(0, 2);
                //else
                //    AppLogWriter.WriteLogEntry("SC Name not found.");
                //if (!string.IsNullOrEmpty(dr[11].ToString()))
                //{
                //    AppLogWriter.WriteLogEntry("Reading SC Date.");
                //    DateTime SCDate = DateTime.FromOADate(Convert.ToDouble(dr[11]));
                //    txtSCDate1.Text = SCDate.Year.ToString().Substring(2) + SCDate.Month.ToString("00");
                //    AppLogWriter.WriteLogEntry("SC Date: " + txtSCDate1.Text);
                //}
                //else
                //    AppLogWriter.WriteLogEntry("SC Date not found.");
                //if (!string.IsNullOrEmpty(dr[12].ToString()))
                //    txtSCCountry1.Text = Convert.ToString(dr[12]).ToUpper().Substring(0, 2);
                //else
                //    AppLogWriter.WriteLogEntry("SC Country not found.");
                if (!string.IsNullOrEmpty(dr[13].ToString()))
                {
                    AppLogWriter.WriteLogEntry("Reading ICE Date.");
                    DateTime IECDate = DateTime.FromOADate(Convert.ToDouble(dr[13]));
                    txtICEDate1.Text = IECDate.Month.ToString("00") + IECDate.Year.ToString();
                    AppLogWriter.WriteLogEntry("ICE Date: " + txtICEDate1.Text);
                }
                else
                    AppLogWriter.WriteLogEntry("IEC Date not found.");
                txtICEName1.Text = Convert.ToString(dr[14]).ToUpper().Substring(0, 6);
                txtIsc1.Text = Convert.ToDouble(dr[15]).ToString("0.00");
                txtVoc1.Text = Convert.ToDouble(dr[16]).ToString("00.0");

                //MessageBox.Show("Done");
                txtIpoints1.Text = Convert.ToDouble(dr[17]).ToString("0.0").Substring(0, 3) +
                            (Convert.ToDouble(dr[18]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[19]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[20]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[21]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[22]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[23]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[24]).ToString("0.0").Substring(0, 3)) +
                            (Convert.ToDouble(dr[25]).ToString("0.0").Substring(0, 3));
                txtVPoints1.Text = (Convert.ToDouble(dr[26]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[27]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[28]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[29]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[30]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[31]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[32]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[33]).ToString("00.0").Substring(0, 4)) +
                            (Convert.ToDouble(dr[34]).ToString("00.0").Substring(0, 4));
                txtIpoints1.ReadOnly = true;
                txtVPoints1.ReadOnly = true;
                AppLogWriter.WriteLogEntry("I Points: " + txtIpoints1.Text);
                AppLogWriter.WriteLogEntry("V Points: " + txtVPoints1.Text);
                IV = txtIpoints1.Text + txtVPoints1.Text;
                AppLogWriter.WriteLogEntry("IV Points: " + IV);
                //MessageBox.Show(IV.ToString());
                string[] iv = new string[2];
                iv[0] = txtIpoints1.Text;
                iv[1] = txtVPoints1.Text;
                //I[0] = Convert.ToDouble(txtIm1.Text);
                //V[0] = Convert.ToDouble(0);
                for (int i = 0; i < 9; i++)
                {
                    //I[i] = new double();
                    I[i] = Convert.ToDouble(Convert.ToDouble(dr[17 + i]).ToString("0.0").Substring(0, 3));
                    AppLogWriter.WriteLogEntry(String.Format("I[{0}] : {1}", i.ToString(), I[i]));
                    //MessageBox.Show(I[i+1].ToString());
                }
                for (int i = 0; i < 9; i++)
                {
                    //V[i] = new double();
                    V[i] = Convert.ToDouble((Convert.ToDouble(dr[26 + i]).ToString("00.0").Substring(0, 4)));
                    AppLogWriter.WriteLogEntry(String.Format("V[{0}] : {1}", i.ToString(), V[i]));
                    //MessageBox.Show(V[i+1].ToString());
                }
                //I[4] = Convert.ToDouble(0);
                //V[4] = Convert.ToDouble(txtVMax1.Text);
                AppLogWriter.WriteLogEntry("Loaded data till I[9] and V[9].");

                //AppLogWriter.WriteLogEntry("ReservedString: " + ReservedString);
                //AppLogWriter.WriteLogEntry("EPCString: " + EPCString);
                //AppLogWriter.WriteLogEntry("UserString: " + UserString);
                AppLogWriter.WriteLogEntry("End LoadData from Excel.");
                miShowGraph.Enabled = true;
            }
            catch (Exception ex)
            {
                AppLogWriter.WriteErrorLog("Error loading data from Excel, Exception: " + ex.Message);
                throw ex;
            }
        }
        private void WriteRes(string s)
        {
            AppLogWriter.WriteLogEntry("Before RM Write.");
            AppLogWriter.WriteLogEntry("RM Data: " + s);
            rfid.BankSelectWrite(AT_UHF_NET.MEMBANK_CODE.BANK_RESERVED, 0, s);
            //MessageBox.Show("Data Written");
            AppLogWriter.WriteLogEntry("After RM Write Data.");
        }
        private void WriteEPC(string s)
        {
            AppLogWriter.WriteLogEntry("Before EPC Write.");
            AppLogWriter.WriteLogEntry("EPC Data: " + s);
            rfid.BankSelectWrite(AT_UHF_NET.MEMBANK_CODE.BANK_EPC, 2, s);
            //MessageBox.Show("Data Written");
            AppLogWriter.WriteLogEntry("After EPC Write Data.");
        }
        private void WriteUser(string s)
        {
            AppLogWriter.WriteLogEntry("Before User Write.");
            AppLogWriter.WriteLogEntry("User Data: " + s);
            rfid.BankSelectWrite(AT_UHF_NET.MEMBANK_CODE.BANK_USER, 0, s);
            //MessageBox.Show("Data Written");
            AppLogWriter.WriteLogEntry("After User Write Data.");
        }

        public string ConvertToHex(string asciiString)
        {
            string hex = "";
            foreach (char c in asciiString)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

        private void miReadTag_Click(object sender, EventArgs e)
        {
            ClearControls();
            miWriteTag.Enabled = false;
            ReadTag();
            miShowGraph.Enabled = true;
            tabControl1.SelectedIndex = 0;
        }

        private void miWriteTag_Click(object sender, EventArgs e)
        {
            try
            {
                if (TagType.Equals("Philips"))
                {
                    ReservedString = ConvertToHex(txtSCName1.Text + txtPVCountry1.Text + txtSCCountry1.Text + txtICEName1.Text);
                    EPCString = txtPeakWattage1.Text + txtPVDate1.Text + txtPVName1.Text;
                    EPCString = ConvertToHex(EPCString);
                    UserString = txtSCDate1.Text + txtPVUSN1.Text + txtModelNo1.Text + txtICEDate1.Text +
                                        txtIm1.Text + txtVMax1.Text + txtFF1.Text + IV;
                }
                else if (TagType.Equals("Alien"))
                {
                    ReservedString = ConvertToHex(txtPVName1.Text + txtPVCountry1.Text.Substring(0, 1));
                    EPCString = txtPVCountry1.Text.Substring(1, 2) + txtICEName1.Text + txtPVUSN1.Text.Substring(0, 1);
                    AppLogWriter.WriteLogEntry("EPCData: " + EPCString);
                    EPCString = ConvertToHex(EPCString);
                    UserString = txtPVUSN1.Text.Substring(1, 9) + txtModelNo1.Text + txtPVDate1.Text + txtICEDate1.Text
                                + txtPeakWattage1.Text + txtIm1.Text + txtVMax1.Text + txtFF1.Text + txtIsc1.Text + txtVoc1.Text + IV;
                }
                AppLogWriter.WriteLogEntry("UserData: " + UserString);
                UserString = UserString.Replace(".", "a");
                //UserString = ConvertToHex(UserString);
                WriteRes(ReservedString);
                WriteEPC(EPCString);
                WriteUser(UserString);
                sbMain.Text = "Tag Data Written Sucessfully.";
                miWriteTag.Enabled = false;
            }
            catch (Exception ex)
            {
                sbMain.Text = ex.Message;
            }
        }

        private void miSearchBarcode_Click(object sender, EventArgs e)
        {
            if (txtBarcode.Text != string.Empty)
            {
                if (MessageBox.Show("Do you want to clear the tag details?",
                                "Confirmation",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    ClearControls();
                    tabControl1.SelectedIndex = 1;
                }
            }
            else
                tabControl1.SelectedIndex = 1;

        }

        private void miClear_Click(object sender, EventArgs e)
        {
            ClearControls();
        }

        private void ClearControls()
        {
            //txtBarcode.Text = string.Empty;
            txtFF.Text = string.Empty;
            txtICEDate.Text = string.Empty;
            txtICEName.Text = string.Empty;
            txtIm.Text = string.Empty;
            txtModelNo.Text = string.Empty;
            txtPeakWattage.Text = string.Empty;
            txtPVCountry.Text = string.Empty;
            txtPVDate.Text = string.Empty;
            txtPVName.Text = string.Empty;
            txtPVUSN.Text = string.Empty;
            txtSCCountry.Text = string.Empty;
            txtSCDate.Text = string.Empty;
            txtSCName.Text = string.Empty;
            txtVMax.Text = string.Empty;
            sbMain.Text = "Done";
            miShowGraph.Enabled = false;
            miWriteTag.Enabled = false;
            miReadTag.Enabled = true;
            txtFF1.Text = string.Empty;
            txtICEDate1.Text = string.Empty;
            txtICEName1.Text = string.Empty;
            txtIm1.Text = string.Empty;
            txtModelNo1.Text = string.Empty;
            txtPeakWattage1.Text = string.Empty;
            txtPVCountry1.Text = string.Empty;
            txtPVDate1.Text = string.Empty;
            txtPVName1.Text = string.Empty;
            txtPVUSN1.Text = string.Empty;
            txtSCCountry1.Text = string.Empty;
            txtSCDate1.Text = string.Empty;
            txtSCName1.Text = string.Empty;
            txtVMax1.Text = string.Empty;
            txtIsc.Text = string.Empty;
            txtIsc1.Text = string.Empty;
            txtVoc.Text = string.Empty;
            txtVoc1.Text = string.Empty;
            txtIpoints1.Text = string.Empty;
            txtVPoints1.Text = string.Empty;
            V = new double[9];
            I = new double[9];
        }

        private void miShowGraph_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(I[0].ToString() + V[0].ToString());
            //MessageBox.Show(I[1].ToString() + V[1].ToString());
            //MessageBox.Show(I[2].ToString() + V[2].ToString());
            //MessageBox.Show(I[3].ToString() + V[3].ToString());
            //MessageBox.Show(I[4].ToString() + V[4].ToString());
            GraphForm gf = new GraphForm();
            gf.I = I;
            gf.V = V;
            gf.ShowDialog();
        }

        private void miClose_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to close the application?", "Are you sure?",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                Application.Exit();
        }

        private void miUploadExcel_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 2;
        }

        private void menuItem12_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 4;
        }
    }
}